package com.fzu.geometa.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzu.geometa.auth.model.LoginTicket;
import com.fzu.geometa.auth.model.po.User;
import com.fzu.geometa.auth.mapper.UserMapper;
import com.fzu.geometa.auth.service.UserService;
import com.fzu.geometa.auth.comm.ActivationConst;
import com.fzu.geometa.auth.util.CommunityUtil;
import com.fzu.geometa.auth.util.MailClient;
import com.fzu.geometa.auth.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.fzu.geometa.auth.comm.UserConst.*;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService, ActivationConst, UserDetailsService {

    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return
     */
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        //空值判断
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        //验证账号是否重复
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, user.getUsername());
        User u = getOne(lqw);
        if (u != null) {
            map.put("usernameMsg", "用户已存在");
            return map;
        }
        //验证邮箱是否被注册
        lqw.clear();
        lqw.eq(User::getEmail, user.getEmail());
        u = getOne(lqw);
        if (u != null) {
            map.put("emailMsg", "邮箱已存在");
            return map;
        }
        //注册用户
        //添加随机字符串
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        //密码加密
        user.setPassword(CommunityUtil.md5(user.getPassword()+ user.getSalt()));
        user.setRole(0);
        //未激活
        user.setStatus(0);
        //激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("https://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        //保存
        save(user);
        //发送激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }

    /**
     * 激活账号
     *
     * @param userId 用户id
     * @param code   激活码
     * @return
     */
    public int activation(int userId, String code) {
        //查询user
        User user = getById(userId);
        if (user.getStatus() == STATUS_ACTIVATED) {
            //已激活
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            //成功激活
            LambdaUpdateWrapper<User> luw = new LambdaUpdateWrapper<>();
            luw.eq(User::getId, user.getId());
            luw.set(User::getStatus, 1);
            //更新状态
            update(luw);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            //激活失败
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录
     *
     * @param username       用户名
     * @param password       密码
     * @param expiredSeconds 过期时间(秒)
     * @return
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }
        //查询账号
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, username);
        User user = getOne(lqw);
        //验证账号
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        //验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }
        //验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!password.equals(user.getPassword())) {
            map.put("passwordMsg", "密码错误!");
            return map;
        }
        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
//        loginTicketMapper.insert(loginTicket);
        // loginTicket存入到Redis中，会序列化为json字符串
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 退出
     * @param ticket 登录凭证
     */
    public void logout(String ticket) {
//        loginTicketMapper.updateStatus(ticket, 1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }

    /**
     *  查询登录凭证
     */
    public LoginTicket findLoginTicket(String ticket) {
//        return loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 修改头像
     * @param id
     * @param headerUrl
     */
    @Override
    public void updateHeader(Integer id, String headerUrl) {
        LambdaUpdateWrapper<User> luw = new LambdaUpdateWrapper<>();
        luw.set(User::getHeaderUrl,headerUrl)
                .eq(User::getId,id);
        update(luw);
        clearCache(id);
    }

    /**
     * 修改密码
     * @param id
     * @param passWord
     * @return
     */
    @Override
    public boolean updatePassword(Integer id, String passWord) {
        LambdaUpdateWrapper<User> luw = new LambdaUpdateWrapper<>();
        luw.set(User::getPassword,passWord)
                .eq(User::getId,id);
        return update(luw);
    }

    @Override
    public User findUserById(int id) {
        //return getById(id);
        User user = getCache(id);
        if (user == null) {
            user = initCache(id);
        }
        return user;
    }

    @Override
    public User findUserByName(String username) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        return getOne(lqw);
    }

    // 1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = baseMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

    /**
     * 根据用户名查询 UserDetails
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = findUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return getUserPrincipal(user);
    }

    private UserDetails getUserPrincipal(User user) {
        // 获得权限
        List<GrantedAuthority> list = new LinkedList<>();
        list.add((GrantedAuthority) () -> {
            switch (user.getRole()) {
                case ROLE_ADMIN:
                    return "ROLE_ADMIN";
                default:
                    return "ROLE_USER";
            }
        });

        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(list)
                .disabled(user.getStatus() == STATUS_NOT_ACTIVATED) // 未激活账号不可用
                .build();
        return userDetails;
    }
}




